<script lang="ts" setup>
import axios from "axios"
import { getToken } from "@/utils/cache/cookies"
import type { FormInstance, FormRules, UploadProps } from "element-plus"
import { ElMessage } from "element-plus"
import { Delete } from "@element-plus/icons-vue"
import { defineProps, withDefaults, ref } from "vue"
import { deleteUploadFile } from "@/api/upload/index.ts"
const props = withDefaults(
  defineProps<{
    uploadTips?: string
    fileType?: string
    limit?: number | string
  }>(),
  {
    uploadTips: "jpg/png files with a size less than 500kb",
    fileType: ".png,.jpg,.jpeg",
    limit: 1
  }
)

const fileList = ref([])
const imageUrl = ref("")
const cloudPath = `admin-ui/${Date.now()}.jpg`

const uploadUrl = ref("")
const uploadHeaders = ref({})
const uploadData = ref({})
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!")
    return false
  }

  return new Promise<void>((resolve, reject) => {
    axios({
      url: "https://fc-mp-54078533-0cb4-46b0-aa85-4d88df83247f.next.bspapp.com/api/wallpaper/upload/getUploadFileOptions",
      headers: {
        token: getToken()
      },
      params: {
        cloudPath
      }
    })
      .then((res) => {
        const { data } = res
        uploadUrl.value = data.uploadFileOptions.url // 上传地址
        uploadHeaders.value = {
          token: getToken()
        }
        uploadData.value = {
          key: data.uploadFileOptions.formData.key,
          name: data.uploadFileOptions.name,
          token: data.uploadFileOptions.formData.token
        }
        resolve()
      })
      .catch((error) => {
        reject(error)
      })
  })
}

const handleAvatarSuccess = (response, uploadFile) => {
  console.log(response, "response---------")
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  ElMessage.success("上传成功")
}
const handleError = (error) => {
  console.log(error, "error---------")
}

const handleDelete = async (e) => {
  e.stopPropagation()
  const result = await deleteUploadFile({ files: uploadData.value.key })
  console.log(result, "result---------")
  if (result.code === 200) {
    ElMessage.success("删除成功")
    imageUrl.value = ""
  }
}

const fileChange = (uploadFile, fileList) => {
  // ruleForm.value.file = uploadFile
  // if (fileList.length !== 0) {
  //   ruleFormRef.value.validateField("file")
  // }
}

const fileRemove = (uploadFile, fileList) => {
  // if (fileList.length === 0) {
  //   ruleForm.value.file = null
  //   ruleFormRef.value.validateField("file")
  // }
}
</script>
<template>
  <el-upload
    ref="uploadRef"
    class="upload-demo"
    :action="uploadUrl"
    v-model="fileList"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :on-error="handleError"
    :before-upload="beforeAvatarUpload"
    :limit="limit"
    :accept="fileType"
    :on-change="fileChange"
    :on-remove="fileRemove"
    :headers="uploadHeaders"
    :data="uploadData"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-button type="danger" class="del-icon" v-if="imageUrl" :icon="Delete" circle @click="handleDelete" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>

    <template #tip>
      <div class="el-upload__tip">{{ uploadTips }}</div>
    </template>
  </el-upload>
</template>

<style lang="scss" scoped>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  position: relative;
}
.del-icon {
  position: absolute;
  right: 10px;
  bottom: 10px;
  display: none;
}
</style>

<style>
.el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-upload:hover .del-icon {
  display: block;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
